package com.lin.sunnyweather.ui.view

import android.animation.ObjectAnimator
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.util.Log
import android.view.View
import android.view.animation.LinearInterpolator
import com.lin.sunnyweather.R

class HeadView : View {

    private val paint = Paint()
    private val clipPath = Path()
    private var headBitmap = BitmapFactory.decodeResource(resources, R.drawable.ic_ultraviolet)
    private var headBitmapRect = Rect()
    private var rect = Rect()
    private val objectAnimator = ObjectAnimator
        .ofFloat(this, "rotation", 0f, 360f)

    constructor(context: Context) : super(context) {
        init()
    }

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
        init()
    }

    constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(
        context,
        attrs,
        defStyle
    ) {
        init()
    }

    private fun init() {
        paint.color = Color.WHITE
        paint.isAntiAlias = true
        paint.isFilterBitmap = true
        objectAnimator.apply {
            interpolator = LinearInterpolator()
            duration = 8000
            repeatCount = -1
            start()
        }
    }

    /**
     * 设置头像
     */
    fun setHeadBitmap(bitmap: Bitmap) {
        headBitmap = bitmap
        headBitmapRect = Rect(0, 0, headBitmap.width, headBitmap.height)

    }

    override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
        super.onLayout(changed, left, top, right, bottom)
        Log.d("view", "onLayout: width:$width,height:$height ")
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        rect = Rect(0, 0, width, height)
        clipPath.addCircle(width / 2.0f, height / 2.0f, width / 2.0f, Path.Direction.CCW)
        Log.d("view", "onSizeChanged: width:$width,height:$height ")
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        canvas.clipPath(clipPath)
        canvas.drawBitmap(
            headBitmap,
            headBitmapRect,
            rect,
            paint
        )
    }
}